from django.http import HttpResponse

# Create your views here.
def add_cookie(request):
    # 存储客户端用response
    response = HttpResponse('设置cookie')
    # 过期时间，单位s
    max_age = 7*24*60*60
    response.set_cookie("username", "zhiliao", max_age)
    return response


def delete_cookie(request):
    """
    实际上删除 cookie 就是将指定的 cookie 的值设置为空的字符
    串，然后使用将他的过期时间设置为 0 ，也就是浏览器关闭后就过期。
    :param request:
    :return:
    """
    response = HttpResponse()
    response.delete_cookie("username")
    return response



def get_cookie(request):
   #  方式一
   username = request.COOKIES.get('username')
   print(username)
   # 方式二
   # for key,value in request.COOKIES.items():
   #     print(f"key: {key}= value: {value}")
   return HttpResponse("get cookie success")



def add_session(request):
    # 存储在服务端用request
    # 如果没有设置session过期时间，默认是2周后过期
    request.session['user_id'] = 'zhiliao'
    # 如果设置成0，那么浏览器关闭后，session就会过期并
    request.session.set_expiry(0)
    return HttpResponse("add session success")


def get_session(request):
    user_id = request.session.get('user_id')
    print(user_id)
    return HttpResponse("get session success")
